package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.exception.ExceptionCompletion;
import com.fwtai.pay.wechat.ToolWechat;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolCode;
import com.fwtai.tool.ToolFile;
import com.fwtai.tool.ToolString;
import com.fwtai.web.GoodsCodeDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 商品防伪码业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2024-02-20 12:03:46
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class GoodsCodeService{

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  private final GoodsCodeDao goodsCodeDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public GoodsCodeService(final GoodsCodeDao goodsCodeDao,final ThreadPoolTaskExecutor taskExecutor){
    this.goodsCodeDao = goodsCodeDao;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request,5);
      final String p_goods_id = "goods_id";
      final String p_total = "total";
      final String validate = ToolClient.validateField(formData,p_goods_id,p_total);
      if(validate != null) return validate;
      final String len_goods_id = formData.getString(p_goods_id);
      if(len_goods_id != null && len_goods_id.length() > 19){
        return ToolClient.createJsonFail("商品名称有误");
      }
      final Long goodsId = formData.getLong(p_goods_id);
      final Integer total = formData.getInteger(p_total);
      if(total == null){
        return ToolClient.createJsonFail("输入生成防伪码数量");
      }
      if(total > 500){
        return ToolClient.createJsonFail("数量不宜大于500个");
      }
      final ArrayList<HashMap<String,Object>> list = new ArrayList<>(total);
      final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
      final long folder = new IdBuilder().getId121L();
      final String prePath = "/qrcode/" + folder;
      final File dir = new File(baseDir+prePath);
      if(!dir.exists()){
        dir.mkdirs();
      }
      for(int i = total - 1; i >= 0; i--){
        final HashMap<String,Object> map = new HashMap<>(3);
        map.put("kid",new IdBuilder().getId121L());
        map.put("goods_id",goodsId);
        final String code = ToolCode.securityCode();
        map.put("code",code);
        final String path = ToolWechat.getAppletCode(baseDir +"/"+ prePath +"/"+code+".png",code);
        if(path == null){
          throw new ExceptionCompletion("生成小程序码出错，稍候重试");
        }
        list.add(map);
      }
      final int rows = goodsCodeDao.addGoodsCode(list);
      if(rows > 0){
        final HashMap<String,Object> data = new HashMap<>(1);
        data.put("folder",(baseDir + prePath));
        return ToolClient.queryJson(data);
      }
      return ToolClient.executeRows(rows);
    },taskExecutor).join();
  }

  public void queryDown(final Long kid,final String name,final HttpServletResponse response){
    CompletableFuture.runAsync(()->{
      if(kid == null){
        ToolClient.responseJson(ToolClient.jsonValidateField(),response);
        return;
      }
      final String code = goodsCodeDao.queryById(kid);
      if(code == null){
        ToolClient.responseJson(ToolClient.createJsonFail("未找到对应的防伪码"),response);
        return;
      }
      final byte[] data = ToolWechat.getAppletCode(code);
      if(data == null){
        throw new ExceptionCompletion("生成小程序码出错，稍候重试");
      }
      ToolClient.download(data,name+code+".png",response);
    },taskExecutor).join();
  }

  public void downFile(final HttpServletRequest request,final HttpServletResponse response){
    CompletableFuture.runAsync(()->{
      final PageFormData formData = new PageFormData(request,2);
      final String p_folder = "folder";
      final String validate = ToolClient.validateField(formData,p_folder);
      if(validate != null){
        ToolClient.responseJson(validate,response);
      }
      final String folder = formData.getString(p_folder);
      final String last = folder.substring(folder.lastIndexOf("/"));//获取文件夹名称
      final String zipFile = folder + last + ".zip";//压缩包名称
      try {
        ToolFile.zipCompressFolder(folder,zipFile);//压缩
        ToolClient.download(zipFile,response);//下载
        ToolClient.delFileByThread(folder);//删除文件及文件夹内的文件及删除自身文件夹
      } catch (final Exception ignored){}
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> goodsCodeDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> goodsCodeDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }

  public String getGoodsList(){
    return CompletableFuture.supplyAsync(()->ToolClient.queryJson(goodsCodeDao.getGoodsList()),taskExecutor).join();
  }
}